package com.compass.mobile.ui.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.activity.viewModels
import androidx.core.content.ContentProviderCompat.requireContext
import androidx.fragment.app.viewModels
import androidx.leanback.widget.ArrayObjectAdapter
import androidx.leanback.widget.BaseGridView
import androidx.leanback.widget.FocusHighlight
import androidx.leanback.widget.FocusHighlightHelper
import androidx.lifecycle.lifecycleScope
import com.compass.mobile.callback.OnItemClickListener
import com.compass.mobile.databinding.AvtivitySearchDoctorDeptBinding
import com.compass.mobile.framework.base.BaseVBActivity
import com.compass.mobile.framework.constant.KEY_KEYWORDS
import com.compass.mobile.framework.constant.KEY_TYPE
import com.compass.mobile.framework.ext.gone
import com.compass.mobile.framework.ext.textChangeFlow
import com.compass.mobile.framework.ext.visible
import com.compass.mobile.framework.ifly.IFlyHelper
import com.compass.mobile.framework.ifly.IFlyOptCallback
import com.compass.mobile.framework.utils.FocusViewUtils
import com.compass.mobile.framework.utils.dpToPx
import com.compass.mobile.models.DepartmentBean
import com.compass.mobile.models.Doctor
import com.compass.mobile.presenters.DepartmentPresenter
import com.compass.mobile.presenters.DoctorPresenter
import com.compass.mobile.ui.viewModel.DoctorViewModel
import com.compass.mobile.ui.viewModel.InquiryViewModel
import com.compass.mobile.widget.MyBridgeAdapter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch

/**
 * Description：搜索科室和医生
 * Date:2024/7/4 16:16
 */
class SearchDoctorAndDepartmentActivity : BaseVBActivity<AvtivitySearchDoctorDeptBinding>() {

    companion object {
        fun start(context: Context,keyWords :String?,comeType:String?) {
            val intent = Intent(context, SearchDoctorAndDepartmentActivity::class.java)
            intent.putExtra(KEY_KEYWORDS,keyWords)
            intent.putExtra(KEY_TYPE,comeType)
            context.startActivity(intent)
        }
    }
    private var comeType: String? = null
    private var keyWords: String? = null
    private val inquiryViewModel: InquiryViewModel by viewModels()
    private val doctorViewModel: DoctorViewModel by viewModels()
    private var doctors: MutableList<Doctor> = mutableListOf()

    private var depts: MutableList<DepartmentBean>  = mutableListOf()
    private lateinit var arrayDoctorAdapter: ArrayObjectAdapter
    private lateinit var arrayObjectAdapter: ArrayObjectAdapter

    override fun initView(savedInstanceState: Bundle?) {
//        FocusViewUtils.scaleView(mBinding.edtKeyWords, 0)
        keyWords = intent.getStringExtra(KEY_KEYWORDS)
        comeType = intent.getStringExtra(KEY_TYPE)
        keyWords?.let {
            mBinding.edtKeyWords.setText(keyWords)
        }
        initSpecialColumn()
        mBinding.caseDept.post {
            // 使用获取到的宽度
            val width = mBinding.caseDept.width
            specialColumn(width)
        }
        mBinding.edtKeyWords.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                //点击了搜索按钮后，需要隐藏软键盘
                keyWords = mBinding.edtKeyWords.text.toString().trim()
                getRecommendDoctor()

            }
            false
        }

        mBinding.edtKeyWords.setOnFocusChangeListener { v, hasFocus ->
            if(mInit){
                if (hasFocus) {
                    // EditText获得了焦点
                    IFlyHelper.getText(this@SearchDoctorAndDepartmentActivity,textCallback)
                } else {
                    // EditText失去了焦点
                    IFlyHelper.cancelText()
                }
            }
        }

        mBinding.edtKeyWords.textChangeFlow()
            .distinctUntilChanged()
            .debounce(500)
            .flowOn(Dispatchers.IO)
            .onEach {
                //这里走查询接口
                keyWords = mBinding.edtKeyWords.text.toString().trim()
                getRecommendDoctor()
            }
            .launchIn(lifecycleScope)

        getRecommendDoctor()

        GlobalScope.launch(Dispatchers.Main) {
            delay(1000)
            IFlyHelper.initIFly(this@SearchDoctorAndDepartmentActivity,flyCallback)
        }

    }
    private var mInit:Boolean = false
    private val flyCallback = object :IFlyOptCallback{
        override fun onSuccess(text: String?) {
            mInit = true
            IFlyHelper.getText(this@SearchDoctorAndDepartmentActivity,textCallback)
//            mBinding.edtKeyWords.requestFocus()
        }

        override fun onFail(code: Int, text: String?) {
        }
    }
    private val textCallback = object : IFlyOptCallback {
        override fun onSuccess(text: String?){
            text.let {
                mBinding.edtKeyWords.setText(it)
                mBinding.edtKeyWords.text?.let { it1 -> mBinding.edtKeyWords.setSelection(it1.length) }
            }
        }

        override fun onFail(code: Int, text: String?) {
        }
    }
    private fun getRecommendDoctor() {
//        showLoading()
        when (comeType) {
            //问诊
            "inquiry" -> {
                if(keyWords.isNullOrEmpty()){
                    return
                }
                showLoading()
                doctorViewModel.searchDept(keyWords)
            }
            //预约挂号
            "booking" -> {
                showLoading()
                inquiryViewModel.geDeptListTwoBySort(name = keyWords)
            }
        }


    }

    override fun initData() {
//        showLoading()
//        getRecommendDoctor()

        doctorViewModel.doctorsLiveData.observe(this) {
            dismissLoading()
            it?.let {doctorsList->
                doctors = doctorsList
                arrayDoctorAdapter.clear()
                arrayDoctorAdapter.addAll(0, doctors)
            }
            setEmptyView()
        }

        inquiryViewModel.allDepartmentListLiveData.observe(this){
            dismissLoading()
            it?.let { list ->
                depts = list
                arrayObjectAdapter.clear()
                arrayObjectAdapter.addAll(0, depts)
            }
            doctorViewModel.searchDoctors(keyWords)
        }


        doctorViewModel.departmentListLiveData.observe(this){
            it?.let { list ->
                depts = list
                arrayObjectAdapter.clear()
                arrayObjectAdapter.addAll(0, depts)
            }
            doctorViewModel.searchDoctors(keyWords)

        }

    }



    private fun setEmptyView() {
        if (doctors.isEmpty()){
            mBinding.doctorEmptyView.visible()
        }else{
            mBinding.doctorEmptyView.gone()
        }
        if (depts.isEmpty()){
            mBinding.deptEmptyView.visible()
        }else{
            mBinding.deptEmptyView.gone()
        }


    }


    private val onItemClickListener: OnItemClickListener = object : OnItemClickListener {
        override fun onItemClick(position: Int, view: View) {
            val item = doctors[position]
            item.department?.let {
                when (comeType) {
                    //问诊
                    "inquiry" -> {
                        DoctorHomePageActivity.start(this@SearchDoctorAndDepartmentActivity, item.id, it)
                    }
                    //预约
                    "booking" -> {
                        DoctorRegisterHomeActivity.start(this@SearchDoctorAndDepartmentActivity, item.id, it)
                    }
                }
            }

        }
    }


    @SuppressLint("RestrictedApi")
    fun initSpecialColumn() {
        mBinding.caseItem.verticalSpacing = dpToPx(10)
        val doctorPresenter = DoctorPresenter("2")
        arrayDoctorAdapter = ArrayObjectAdapter(doctorPresenter)
        val itemBridgeAdapter = MyBridgeAdapter(
            this,
            arrayDoctorAdapter, onItemClickListener
        )
        mBinding.caseItem.setAdapter(itemBridgeAdapter)
        mBinding.caseItem.setFocusScrollStrategy(BaseGridView.FOCUS_SCROLL_ITEM)
        arrayDoctorAdapter.addAll(0, doctors)
        FocusHighlightHelper.setupBrowseItemFocusHighlight(
            itemBridgeAdapter,
            FocusHighlight.ZOOM_FACTOR_NONE, false
        )

    }

    private val onDeptItemClickListener: OnItemClickListener = object : OnItemClickListener {
        override fun onItemClick(position: Int, view: View) {
            val item = depts[position]
            comeType?.let {
                DepartmentIntroductionActivity.start(this@SearchDoctorAndDepartmentActivity, item.id, item.code, it)
            }
        }
    }

    @SuppressLint("RestrictedApi")
    fun specialColumn(width: Int) {
        mBinding.caseDept.setNumColumns(2)
        mBinding.caseDept.horizontalSpacing = dpToPx(10)
        mBinding.caseDept.verticalSpacing = dpToPx(10)
        val finalWidth = width - dpToPx(40)
        val departmentPresenter = DepartmentPresenter()
        departmentPresenter.setFinalWidth(finalWidth / 2)
        arrayObjectAdapter = ArrayObjectAdapter(departmentPresenter)
        val itemBridgeAdapter = MyBridgeAdapter(
            this,
            arrayObjectAdapter, onDeptItemClickListener
        )
        mBinding.caseDept.setAdapter(itemBridgeAdapter)
        mBinding.caseDept.setFocusScrollStrategy(BaseGridView.FOCUS_SCROLL_ITEM)
        arrayObjectAdapter.addAll(0, depts)
        FocusHighlightHelper.setupBrowseItemFocusHighlight(
            itemBridgeAdapter,
            FocusHighlight.ZOOM_FACTOR_NONE, false
        )
    }

    override fun onDestroy() {
        super.onDestroy()
        IFlyHelper.unInitIFly()
    }
}
